{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1319cd5e",
   "metadata": {},
   "source": [
    "# 0. 环境准备"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "609e071e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline\n",
    "\n",
    "# 设置pandas可以显示的行数和列数\n",
    "pd.options.display.max_rows = 400\n",
    "pd.options.display.max_columns = None\n",
    "\n",
    "# 忽略warnings\n",
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "\n",
    "#推荐安装插件： nbextensions"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c96ca9d2",
   "metadata": {},
   "source": [
    "# 1.读入数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "0bb3d458",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>date</th>\n",
       "      <th>company</th>\n",
       "      <th>price</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2012-05-18</td>\n",
       "      <td>FB</td>\n",
       "      <td>38.230000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2012-05-21</td>\n",
       "      <td>FB</td>\n",
       "      <td>34.029999</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        date company      price\n",
       "0 2012-05-18      FB  38.230000\n",
       "1 2012-05-21      FB  34.029999"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# date: 日期\n",
    "# company: 公司代码\n",
    "# price: 股价\n",
    "df_stock = pd.read_csv('data/stock_price.csv', parse_dates=['date'])\n",
    "df_stock.head(2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "83f88833",
   "metadata": {},
   "source": [
    "# 2. 使用ETS算法预测所有公司的2022-01-01及以后的股价，每次往后预测1天"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "737f00bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "from statsmodels.tsa.exponential_smoothing.ets import ETSModel"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f1a84487",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "E:\\Anaconda\\setup\\envs\\py4fi\\lib\\site-packages\\statsmodels\\tsa\\base\\tsa_model.py:843: ValueWarning: No supported index is available. Prediction results will be given with an integer index beginning at `start`.\n",
      "  data=self.data,\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "E:\\Anaconda\\setup\\envs\\py4fi\\lib\\site-packages\\statsmodels\\tsa\\base\\tsa_model.py:471: ValueWarning: A date index has been provided, but it has no associated frequency information and so will be ignored when e.g. forecasting.\n",
      "  self._init_dates(dates, freq)\n",
      
      "E:\\Anaconda\\setup\\envs\\py4fi\\lib\\site-packages\\statsmodels\\tsa\\base\\tsa_model.py:843: ValueWarning: No supported index is available. Prediction results will be given with an integer index beginning at `start`.\n",
      "  data=self.data,\n"
     ]
    }
   ],
   "source": [
    "# 对公司和预测日期进行for循环\n",
    "fcst_date_list = pd.date_range( '2022-01-01', df_stock['date'].max() - pd.Timedelta(1, unit='D'), freq='D' )\n",
    "company_list = df_stock['company'].unique()\n",
    "\n",
    "ets_result = []\n",
    "for fcst_date in fcst_date_list:\n",
    "    for company in company_list:\n",
    "        data_train = df_stock[ (df_stock['company']== company) & \n",
    "                     (df_stock['date']<=fcst_date)]\n",
    "        \n",
    "        data_test = df_stock[ (df_stock['company']== company) & \n",
    "                     (df_stock['date']==fcst_date + pd.Timedelta(1, unit='D'))]\n",
    "        \n",
    "        #只有在训练集、测试集都存在的情况下才做预测\n",
    "        if (data_train.shape[0] > 0) & (data_test.shape[0] > 0):\n",
    "            # 把日期变成训练集的index\n",
    "            data_train = data_train[['date','price']].set_index('date')\n",
    "            \n",
    "            # 构建模型\n",
    "            model = ETSModel( data_train['price'] )\n",
    "            fit = model.fit( )\n",
    "            \n",
    "            #预测未来1天\n",
    "            pred_price = fit.get_prediction(start=data_train.shape[0]+1,\n",
    "                                           end = data_train.shape[0]+1).summary_frame()['mean'].values[0]\n",
    "            data_test['pred_price'] = pred_price\n",
    "            data_test['fcst_date'] = fcst_date\n",
    "            ets_result.append( data_test )\n",
    "ets_result = pd.concat( ets_result )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "b13d9fc4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "mape 0.03408034042678108\n"
     ]
    }
   ],
   "source": [
    "# 计算mape\n",
    "ets_result['percentage_error'] = abs(ets_result['pred_price']-ets_result['price'])/ets_result['price']\n",
    "#通常我们用y值作为权重，计算加权平均误差\n",
    "print(\"mape\", np.sum( ets_result['percentage_error']*ets_result['price'] )/np.sum( ets_result['price'] ) ) "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e81acb24",
   "metadata": {},
   "source": [
    "# 3. 使用Arima算法预测所有公司的2022-01-01及以后的股价，每次往后预测1天"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "84543cbd",
   "metadata": {},
   "outputs": [],
   "source": [
    "from statsmodels.tsa.arima.model import ARIMA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "2b03702c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 对公司和预测日期进行for循环\n",
    "fcst_date_list = pd.date_range( '2022-01-01', df_stock['date'].max() - pd.Timedelta(1, unit='D'), freq='D' )\n",
    "company_list = df_stock['company'].unique()\n",
    "\n",
    "arima_result = []\n",
    "for fcst_date in fcst_date_list:\n",
    "    for company in company_list:\n",
    "        data_train = df_stock[ (df_stock['company']== company) & \n",
    "                     (df_stock['date']<=fcst_date)]\n",
    "        \n",
    "        data_test = df_stock[ (df_stock['company']== company) & \n",
    "                     (df_stock['date']==fcst_date + pd.Timedelta(1, unit='D'))]\n",
    "        \n",
    "        #只有在训练集、测试集都存在的情况下才做预测\n",
    "        if (data_train.shape[0] > 0) & (data_test.shape[0] > 0):\n",
    "            # 把日期变成训练集的index\n",
    "            data_train = data_train[['date','price']].set_index('date')\n",
    "            \n",
    "            # 构建模型\n",
    "            model = ARIMA(data_train['price'].values, order=(1,1,0))\n",
    "            fit = model.fit()\n",
    "            \n",
    "            #预测未来1天\n",
    "            pred_price = fit.forecast(1)[0]\n",
    "\n",
    "            data_test['pred_price'] = pred_price\n",
    "            data_test['fcst_date'] = fcst_date\n",
    "            arima_result.append( data_test )\n",
    "arima_result = pd.concat( arima_result )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "e770cb1e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "mape 0.03397359806310875\n"
     ]
    }
   ],
   "source": [
    "# 计算mape\n",
    "arima_result['percentage_error'] = abs(arima_result['pred_price']-arima_result['price'])/arima_result['price']\n",
    "#通常我们用y值作为权重，计算加权平均误差\n",
    "print(\"mape\", np.sum( arima_result['percentage_error']*arima_result['price'] )/np.sum( arima_result['price'] ) ) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "04c5db9b",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
